﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;

namespace AliyunOpenSearch4Net.Base
{
    /// <summary>
    /// Named item collection
    /// </summary>
    /// <typeparam name="TItem">The type of the item.</typeparam>
    /// <typeparam name="TItemValue">The type of the item value.</typeparam>
    public class NamedItemsCollection<TItem, TItemValue>
        where TItem : NamedItem<TItemValue>
    {
        /// <summary>
        /// Gets or sets the items.
        /// </summary>
        /// <value>
        /// The items.
        /// </value>
        public TItem[] Items { get; set; }
    }

    class NamedItemsCollectionConverter<TItem, TItemValue> : JsonConverter
        where TItem : NamedItem<TItemValue>, new()
    {
        public override bool CanConvert(Type objectType)
        {
            return typeof(NamedItemsCollection<TItem, TItemValue>).IsAssignableFrom(objectType);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var result = Activator.CreateInstance(objectType) as NamedItemsCollection<TItem, TItemValue>;            

            var items = new List<TItem>();            

            while(reader.Read())
            {
                if (reader.TokenType == JsonToken.EndObject)
                    break;

                if (reader.TokenType == JsonToken.StartObject)
                    reader.Read();

                var item = new TItem();
                item.Name = reader.Value.ToString();

                reader.Read();
                item.Item = serializer.Deserialize<TItemValue>(reader);

                items.Add(item);
            }           

            result.Items = items.ToArray();

            return result;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }
}
